package com.cloudm.technician.ui.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.cloudm.technician.R
import com.cloudm.technician.data.model.DeviceInfo
import com.cloudm.technician.di.AppComponent
import com.cloudm.technician.extensions.*
import com.cloudm.technician.ui.modules.cloudm_box.channel_list.ChannelListActivity
import com.cloudm.technician.ui.modules.cloudm_box.debug_result.DebugResultActivity
import com.cloudm.technician.ui.modules.cloudm_box.device_debug.DeviceDebugActivity
import com.cloudm.technician.ui.modules.cloudm_box.level_debug.LevelDebugActivity
import com.cloudm.technician.ui.modules.cloudm_box.upload_level_pic.UploadLevelPicActivity
import com.cloudm.technician.ui.modules.cloudm_box.upload_pic.UploadPicActivity
import com.cloudm.technician.ui.modules.common.home.HomeActivity
import com.cloudm.technician.ui.modules.common.login.LoginActivity
import com.umeng.analytics.MobclickAgent
import pub.devrel.easypermissions.AppSettingsDialog
import javax.inject.Inject

/**
 * 作者: wesley
 * 时间: 2017/11/20
 * 描述: 基类的ui
 */
abstract class BaseFragment<T : BasePresenter> : Fragment(), BaseView,
        PromptDialogFragment.OnDialogItemClickListener {

    @Inject
    @JvmField
    var presenter: T? = null

    companion object {
        private const val TAG = "BaseFragment"
    }

    protected lateinit var mContext: Context

    private var loadingFragment: LoadingDialogFragment? = null

    private var appSettingsDialog: AppSettingsDialog? = null

    protected val appComponent: AppComponent
        get() = baseApplication.appComponent

    override val isActive: Boolean
        get() = isAdded

    protected open val resource: Int by lazy {
        R.layout.common_recycler_view
    }

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        context?.let {
            this.mContext = it
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initInject()
        handleArguments()
        initVariables()
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? = inflater.inflate(resource,
            container, false)


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews(view)
        initListener()
    }


    override fun onResume() {
        super.onResume()
        MobclickAgent.onPageStart(javaClass.simpleName)
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPageEnd(javaClass.simpleName)
    }


    override fun onDestroy() {
        super.onDestroy()
        presenter?.cancelRequest()
    }


    private fun handleArguments() {
        arguments?.let {
            handleBundle(it)
        }
    }

    protected fun showLoadingDialog(msg: String) {
        val activity = mContext as? BaseActivity ?: return
        if (activity.isFinishing) return
        loadingFragment = LoadingDialogFragment.newInstance(msg)
        loadingFragment?.show(childFragmentManager, TAG)
    }

    protected fun hideLoadingDialog() {
        loadingFragment?.dismiss()
    }

    protected fun showPromptDialog(message: Int, positiveButton: Int = R.string.ok,
                                   negativeButton: Int = R.string.cancel,
                                   title: Int = R.string.prompt) {
        val activity = mContext as? BaseActivity ?: return
        if (activity.isFinishing) return
        val fragment = PromptDialogFragment.newInstance(message, positiveButton, negativeButton,
                title)
        fragment.listener = this
        fragment.show(childFragmentManager, TAG)
    }

    override fun openLoginActivityAgain() {
        mContext.toast(mContext.resources.getString(R.string.please_login_again))
        val intent = Intent(mContext, LoginActivity::class.java).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        }
        mContext.openActivity(intent)
        appComponent.preferenceHelper.isLogin = false
    }

    override fun openMachineListActivityAgain(msg: String) {
        mContext.toast(mContext.resources.getString(R.string.status_error_jump_to_home))
        val intent = Intent(mContext, HomeActivity::class.java).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            putExtras(Bundle().apply {
                putInt("flag", 1)
            })
        }
        mContext.openActivity(intent)
    }

    protected fun hideSoftKeyboard() {
        val activity = mContext as? AppCompatActivity ?: return
        activity.hideSoftKeyboard()
    }

    protected fun showAppSettingDialog() {
        val activity = mContext as? BaseActivity ?: return
        if (activity.isFinishing) return
        appSettingsDialog = AppSettingsDialog.Builder(this).setPositiveButton(
                R.string.ok).setNegativeButton(R.string.cancel).setRationale(
                R.string.please_set_permissions).setTitle(R.string.permission_setting).build()
        appSettingsDialog?.show()
    }


    protected fun openActivityByStatus(info: DeviceInfo?, finishSelf: Boolean = false) {
        if (info == null) {
            mContext.logger_e(TAG, " openActivityByStatus info is null")
            return
        }

        val intent: Intent?
        val bundle = Bundle().apply {
            putParcelable("info", info)
        }
        when (info.status) {
            2 -> {
                if (info.recordId == null || info.recordId.isNullOrEmpty()) {
                    intent = Intent(mContext, DeviceDebugActivity::class.java).apply {
                        putExtras(bundle)
                    }
                    mContext.openActivity(intent, finishSelf)
                } else {
                    intent = Intent(mContext, DebugResultActivity::class.java).apply {
                        putExtras(bundle)
                    }
                    mContext.openActivity(intent, finishSelf)
                }
            }

            3 -> {
                intent = Intent(mContext, UploadPicActivity::class.java).apply {
                    putExtras(bundle)
                }
                mContext.openActivity(intent, finishSelf)
            }

            5 -> {
                intent = Intent(mContext, LevelDebugActivity::class.java).apply {
                    putExtras(bundle)
                }
                mContext.openActivity(intent, finishSelf)
            }

            6 -> {
                intent = Intent(mContext, UploadLevelPicActivity::class.java).apply {
                    putExtras(bundle)
                }
                mContext.openActivity(intent, finishSelf)
            }

            7 -> {
                intent = Intent(mContext, ChannelListActivity::class.java).apply {
                    putExtras(bundle)
                }
                mContext.openActivity(intent, finishSelf)
            }

            else -> {
                mContext.logger_e(TAG, " status = ${info.status}")
            }
        }
    }

    override fun onPositiveButtonClick() {

    }

    /**
     * 注入
     */
    protected abstract fun initInject()


    /**
     * 处理界面跳转时参数传递
     */
    protected abstract fun handleBundle(bundle: Bundle)


    /**
     * 初始化变量
     */
    protected abstract fun initVariables()


    /**
     * 初始化view
     */
    protected abstract fun initViews(view: View)


    /**
     * 初始化点击事件
     */
    protected abstract fun initListener()


}